﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Collections;
using DA_CLIENT.Controls;
using DevExpress.Utils.Menu;
using Messenger.Lib;
using System.Runtime.Remoting.Services;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels.Http;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using MessengerChatRoom;
using System.Net;
using DevExpress.XtraBars.Helpers;
namespace DA_CLIENT
{
    public partial class FrmMain : DevExpress.XtraEditors.XtraForm
    {
        private MarshalByRefObject objConnected;

        public MarshalByRefObject ObjConnected
        {
            get { return objConnected; }
            set { objConnected = value; }
        }
        public FrmMain()
        {
            
        }
        public FrmMain(MarshalByRefObject obj)
        {
            this.objConnected = obj;
            InitializeComponent();
            SkinHelper.InitSkinPopupMenu(barSubItem4);
            LoadContact();
        }
        /// <summary>
        /// Load Danh bạ
        /// </summary>
        private void LoadContact()
        {
            statusBar.Text = "Đang tải danh sách bạn bè ....";
            Console.WriteLine("Đang tải danh sách bạn bè ....");
            ArrayList contacts = null;
            try
            {
                contacts = Global.server.GetContacts(Global.username);
                statusBar.Text = "Đã tải danh sách bạn bè thành công ";
                Console.WriteLine("Đã tải danh sách bạn bè thành công ");
                int i = 20;
                pnlContacts.Controls.Clear();
                Global.contactList.Clear();
               
                //Duyet username
                foreach(object username in contacts){
                    //Khởi tạo đối tượng controls
                    ControlContact controlContact = new ControlContact();
                    controlContact.Location = new System.Drawing.Point(8, i);
                    controlContact.Size = new System.Drawing.Size(pnlContacts.Width - 16, 16);
                    controlContact.DoubleClick += new System.EventHandler(controlContact.Contact_Click); // Sự kiện double click lên contact
				    //Hiện icon online hay offline
                    controlContact.Online = Global.server.IsVisible(username as String);
                    //Hiển thị tên đầy đủ
                    controlContact.DisplayFullName = Global.server.GetFullName(username as String);
                    controlContact.Contact = username as string;
                    pnlContacts.Controls.Add(controlContact);
                    Global.contactList.Add(controlContact);
                    i += 20;
                }
                timerMessenger.Enabled = true;
                timerContactUpdate.Enabled = true;
            }
            catch {
                Console.WriteLine("Danh sách bạn bè rỗng ! ");
                statusBar.Text = "Danh sách bạn bè rỗng ! ";
                return;
            }
            Console.ReadLine();
        }

        
      
        private IDXMenuManager menuManager;
        public IDXMenuManager MenuManager
        {
            get { return menuManager; }
            set { menuManager = value; }
        }

        private DXPopupMenu CreatePopupMenu()
        {
            DXPopupMenu menu = new DXPopupMenu();
            menu.Items.Add(new DXMenuItem("Thêm bạn bè", new EventHandler(OnAddContactClick), DA_CLIENT.Properties.Resources.user_male_add, null, DA_CLIENT.Properties.Resources.user_male_add,null));
            menu.Items.Add(new DXMenuItem("Xóa bạn bè", new EventHandler(OnRemoveContactClick), DA_CLIENT.Properties.Resources.deletered, null, DA_CLIENT.Properties.Resources.deletered, null));
            menu.Items.Add(new DXMenuItem("Làm mới danh sách", new EventHandler(OnRefestContactClick), DA_CLIENT.Properties.Resources.arrow_refresh, null, DA_CLIENT.Properties.Resources.arrow_refresh, null));
            return menu;
        }

        private void OnRefestContactClick(object sender, EventArgs e)
        {
            
        }

        private void OnRemoveContactClick(object sender, EventArgs e)
        {
            
        }

        private void OnAddContactClick(object sender, EventArgs e)
        {
            FrmAddContact frmAddContact = new FrmAddContact();
            frmAddContact.ShowDialog();
           
        }

       

        private void FrmMain_Load(object sender, EventArgs e)
        {
            
        }

        private void textEdit1_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void panelControl1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {

        }

        private void buttonEdit1_MouseDown(object sender, MouseEventArgs e)
        {

        }

        private void RightClictContact(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                MenuManagerHelper.ShowMenu(CreatePopupMenu(), pnlContacts.LookAndFeel, menuManager, pnlContacts, pnlContacts.PointToClient(MousePosition));
                //Application.DoEvents();
            }
        }

        private void pnlContacts_MouseClick(object sender, MouseEventArgs e)
        {
            Console.WriteLine("ta da click vao day");
            Console.ReadLine();
        }

        private void menuXyLy(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Console.WriteLine("ta da click vao menu day");
            Console.ReadLine();
        }
        bool Check = false; // Biến cờ kiểm tra đã Check trạng thái của 1 người dùng hay chưa?
        private void timerContactUpdate_Tick(object sender, EventArgs e)
        {
            try
            {
                foreach (object username in Global.contactList)
                {
                    // Thay đổi biến cờ khi bạn bè thay đổi trạng thái.
                    if (((ControlContact)username).Online != Global.server.IsVisible((username as ControlContact).Contact)) 
                        Check = !Check;
                    // Cập nhật lại trạng thái trong Contact List
                    ((ControlContact)username).Online = Global.server.IsVisible((username as ControlContact).Contact);
                       
                }
                pnlContacts.Update();
            }
            catch
            {
                return;
            }
        }
        //Phương thức nhận tin nhắn
        private void timerMessengerRecives(object sender, EventArgs e)
        {
            LetterReceive letter;
            try
            {
                letter = Global.server.Receive(Global.username);
            }
            catch
            {
                return;
            }
            if (letter.From == "")
            {
                return;
            }
            if (Global.windowList.Contains(letter.From))
            {
                if (letter.Message == "BUZZ IT")
                {
                    ((FrmMessenger)Global.windowList[letter.From]).Focus();
                }
                ((FrmMessenger)Global.windowList[letter.From]).AddText(letter.From, letter.Message);

            }
            else
            {
                FrmMessenger frmMessenger = new FrmMessenger();
                frmMessenger.contact = letter.From;
                frmMessenger.Text = letter.From + " - Tin nhắn trực tiếp.";
                frmMessenger.AddText(letter.From, letter.Message);
                Global.windowList.Add(letter.From, frmMessenger);
                frmMessenger.Show();
            }
        }

        private void SignIn()
        {
            FrmIndex fIndex = new FrmIndex();
            fIndex.Show();
            switch (this.ShowDialog(this))
            {
                case DialogResult.OK:
                    Global.username = "";
                    timerContactUpdate.Enabled = true;
                    timerMessenger.Enabled = true;
                    this.LoadContact();
                    break;
            }
        }

        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Global.server.SignOut(Global.username);
            pnlContacts.Controls.Clear();
            Global.contactList.Clear();
            Global.username = "";
            FrmMain fMain = new FrmMain();
            timerContactUpdate.Enabled = false;
            timerMessenger.Enabled = false;
            fMain.Hide();
            SignIn();
        }

        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                Global.server.SignOut(Global.username); // Người dùng bấm Exit thì cũng sẻ SignOut nick lun.
            }
            finally
            {
                Application.Exit();
            }
        }

        // Tham gia một room đã có sẵn
        private void barButtonItem4_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            FrmJoinRoom fjr = new FrmJoinRoom();
            fjr.Show();
        }

        // Delegate để UnregisterChannel khi FormChatRoom đóng
        bool ChatRoomClosed = false;
        public void GetValue(Boolean b)
        {
            ChatRoomClosed = b;
            if (ChatRoomClosed)
                ChannelServices.UnregisterChannel(channelChatRoom);
        }

        TcpChannel channelChatRoom;
        // Mở một chat room mới.
        private void barButtonItem3_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            // Khởi tạo kênh liên lạc với remote Object.
            channelChatRoom = new TcpChannel(7070);
            ChannelServices.RegisterChannel(channelChatRoom, false);

            // Ở đây sẻ sử dụng Singleton để duy trì trạng thái với nhiều kết nối Client 
            RemotingConfiguration.RegisterWellKnownServiceType(typeof(SampleObject), Global.username.ToString(), WellKnownObjectMode.Singleton); // Cho Server chat room

            // Mở Room
            if (OpenRoom() == 0)
            {
                ChannelServices.UnregisterChannel(channelChatRoom);
                channelChatRoom = null;
            }
        }

        TcpChannel chan;
        private int OpenRoom()
        {
            ArrayList alOnlineUser = new ArrayList();
            FrmChatRoom objChatWin;

            if (true) // lãng xẹt, nhát sửa =))
            {
                chan = new TcpChannel();
                //ChannelServices.RegisterChannel(chan, false);
                chan = null;
                IPHostEntry temp = Dns.GetHostByName(Dns.GetHostName().ToString());
                string IP = temp.AddressList[0].ToString();
                objChatWin = new FrmChatRoom();
                objChatWin.MyGetData = new FrmChatRoom.GetString(GetValue);
                objChatWin.remoteObj = (SampleObject)Activator.GetObject(typeof(MessengerChatRoom.SampleObject), "tcp://" + IP + ":7070/" + Global.username);

                if (!objChatWin.remoteObj.JoinToChatRoom(Global.username))
                {
                    MessageBox.Show(Global.username + " đã đăng nhập rồi!. Có thể mạng bị lag, hãy thử lại sau!");
                    ChannelServices.UnregisterChannel(chan);
                    chan = null;
                    objChatWin.Dispose();
                    return 1; // 1: da dang nhap roi
                }
                objChatWin.key = objChatWin.remoteObj.CurrentKeyNo();
                objChatWin.yourName = Global.username;
                objChatWin.Show();
                return 2; // 2 : Dang nhap cong
            }
            else
            {
                MessageBox.Show("Đã có lỗi xảy ra khi tạo Room Chat, vui lòng thử lại!");
                chan = null;
                return 0; // 0: Loi
            }
        }

    }
    
}